package com.meitianhui.convenitenbuy.module.wallet.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.zxing.WriterException;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.wallet.contract.WalletCouponDetailContract;
import com.meitianhui.convenitenbuy.module.wallet.di.DaggerWalletComponent;
import com.meitianhui.convenitenbuy.module.wallet.di.WalletModule;
import com.meitianhui.convenitenbuy.module.wallet.model.CouponBean;
import com.meitianhui.convenitenbuy.module.wallet.model.CouponDetailBean;
import com.meitianhui.convenitenbuy.module.wallet.presenter.WalletCouponDetailPresenter;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.WordWrapView;
import com.meitianhui.convenitenbuy.widget.dialog.SettingStoreDialog;
import com.meitianhui.convenitenbuy.zxing.encoding.EncodingHandler;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import rx.Observable;
import rx.functions.Action1;

public class WalletCouponDetailActivity extends BaseToolbarActivity implements WalletCouponDetailContract.View {
    @Inject
    WalletCouponDetailPresenter mPresenter;

    private ImageView img_erweima;//二维码
    private ImageView h_phone;//打电话

    private ImageView ivLogo;//商家图标
    private Button btn_tuikuan;//申请退款
    private TextView tvCoupon, tvCouponTitle;//再次购买
    private ScrollView elasticScrollView;
    private String imageUrl;
    private String cataid;//
    private TextView tvAddress, tvStoreName, tvEffectTime, tvTime;

    private TextView txt_des;//活动描述
    private TextView txt_use_condition;//使用条件
    private TextView txt_code;//二维码字符串

    private LinearLayout lay_bg;//
    private WordWrapView view_wordwrap;
    private SettingStoreDialog settingStoreDialog;
    CouponDetailBean mBean;
    CouponBean.DiscountCard argument;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerWalletComponent.builder().appComponent(App.getInstance().getAppComponent()).walletModule(new WalletModule(this)).build().inject(this);

        setTbTitle(getString(R.string.wallet_coupon));

        Intent intent = getIntent();
        argument = intent.getParcelableExtra(Constants.ARGUMENT);
        imageUrl = intent.getStringExtra("url");

        registerPush();
        initId();
        initInfo();
    }

    private void registerPush() {
        Disposable disposable = RxBus.get().toFlowable(EventBean.class).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean bean) throws Exception {
                if (bean != null) {
                    if (bean.type == Constants.EVENT_TYPE_REFRESH) {
                        initInfo();
                    }
                }
            }
        });
        mCompositeDisposable.add(disposable);
    }

    private void initInfo() {
        mPresenter.getCouponDetail(argument.getSku_id());
    }


    private void initId() {
        lay_bg = getViewById(R.id.lay_bg);
        img_erweima = getViewById(R.id.img_erweima);
        h_phone = getViewById(R.id.h_phone);
        btn_tuikuan = getViewById(R.id.btn_tuikuan);
        tvAddress = getViewById(R.id.tv_address);
        tvStoreName = getViewById(R.id.tv_storename);
        tvEffectTime = getViewById(R.id.tv_effecttime);
        tvTime = getViewById(R.id.tv_time);
        elasticScrollView = getViewById(R.id.scrollview);
        tvCoupon = getViewById(R.id.tv_count);
        ivLogo = getViewById(R.id.iv_logo);
        tvCouponTitle = getViewById(R.id.coupon_title);
        txt_des = getViewById(R.id.txt_des);
        txt_use_condition = getViewById(R.id.txt_use_condition);
        txt_code = getViewById(R.id.txt_code);
        view_wordwrap = getViewById(R.id.view_wordwrap);

        cataid = argument.getCategory_id();
        if (cataid.equals(Constants.CONS_CASH)) {//现金购买
            lay_bg.setBackgroundResource(R.color.wallet_coupon_detail_cash);
        } else if (cataid.equals(Constants.CONS_LIQUAN)) {//礼券兑换
            lay_bg.setBackgroundResource(R.color.wallet_coupon_detail_coupon);
        } else if (cataid.equals(Constants.CONS_FREE)) {//免费领取
            lay_bg.setBackgroundResource(R.color.wallet_coupon_detail_free);
        }

        RxUtils.bindEvents(h_phone, this);
        RxUtils.bindEvents(btn_tuikuan, this);
    }

    @Override
    protected int setView() {
        return R.layout.activity_wallet_coupon_detail;
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.h_phone:
                settingStoreDialog = new SettingStoreDialog(WalletCouponDetailActivity.this, new SettingStoreDialog.AlertDialogListener() {
                    @Override
                    public void onConfirmClick() {
                        settingStoreDialog.dismiss();
                        RxPermissions rxPermissions = new RxPermissions(WalletCouponDetailActivity.this);
                        rxPermissions
                                .requestEach(Manifest.permission.CALL_PHONE)
                                .subscribe(permission -> {
                                    if (permission.granted) {
                                        Observable.timer(2000, TimeUnit.MILLISECONDS)
                                                .compose(RxUtils.rxSchedulerHelper()).subscribe(new Action1<Long>() {
                                            @Override
                                            public void call(Long aLong) {
                                                try {
                                                    Intent phoneIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mBean.getContact_tel()));//拨打电话
                                                    startActivity(phoneIntent);
                                                } catch (SecurityException e) {
                                                    TipUtils.showToast(App.getInstance(), "无权限");
                                                }
                                            }
                                        });
                                    } else if (permission.shouldShowRequestPermissionRationale) {
                                        TipUtils.showToast(App.getInstance(), "无权限");
                                    }
                                });

                    }

                    @Override
                    public void onCancelClick() {
                        settingStoreDialog.dismiss();

                    }
                });
                break;
            case R.id.btn_tuikuan:
                break;
        }
    }

    @Override
    protected void onRefreshData() {
        initInfo();
    }


    @Override
    public void getCouponDetailBack(boolean result, String msg, CouponDetailBean bean) {
        refreshFinish();
        if (result) {
            elasticScrollView.setVisibility(View.VISIBLE);
            setData(bean);
        } else {
            TipUtils.showToast(App.getInstance(), msg);
        }
    }

    private void setData(CouponDetailBean bean) {
        mBean = bean;
        Bitmap qrcodeBitmap = null;
        String sku_code = bean.getSku_code();
        try {
            qrcodeBitmap = EncodingHandler.createQRCode("YHQ" + sku_code, 260);
        } catch (WriterException e) {
            e.printStackTrace();
            TipUtils.showToast(App.getInstance(), getString(R.string.wallet_payment_setting_fail));
        }
        img_erweima.setImageBitmap(qrcodeBitmap);
        Animation a = AnimationUtils.loadAnimation(this, R.anim.zoom_in);
        img_erweima.setAnimation(a);


        tvAddress.setText(bean.getAddress());
        tvStoreName.setText(bean.getStores_name());
        //tvEffectTime.setText("截止日期:" + menDianCardBean.getExpired_date().substring(0,10));
        tvTime.setText(bean.getExpired_date().substring(0, 10));
        tvCouponTitle.setText(bean.getTitle());

        txt_use_condition.setText("需消费" + bean.getLimit_amount() + "元可用");
        txt_des.setText(bean.getCoupon_desc());
        txt_code.setText("验证码 " + sku_code);


        String label = bean.getLabel();
        if (label != null && !label.equals("")) {
            String[] attr = label.split("\\|");
            view_wordwrap.removeAllViews();
            for (int i = 0; i < attr.length; i++) {
                View v = LayoutInflater.from(this).inflate(
                        R.layout.helpyoudiscount_tv, null);
                TextView textview = (TextView) v.findViewById(R.id.tv);
                textview.setText(attr[i]);
                view_wordwrap.addView(v);
            }
        }

        GlideUtils.setCircleImage(this,imageUrl, R.mipmap.wallet_coupon_item_default, R.mipmap.wallet_coupon_item_default, ivLogo);
    }


}
